import request from '@/utils/request'
import { post, get, put, del } from '@/utils/api'
import { API_ENDPOINTS } from '@/config/api'

/**
 * 上传知识库附件
 * @param {File|Blob} file 上传的文件对象
 * @returns {Promise}
 */
export const uploadKnowledgeAttachment = (file) => {
  const formData = new FormData()
  formData.append('file', file)

  return request({
    method: 'post',
    url: API_ENDPOINTS.KNOWLEDGE.UPLOAD,
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    timeout: 20000, // 文件上传超时时间设置为20秒
  })
}

/**
 * 创建知识库
 * @param {number} fileId - 文件ID
 * @param {string} title - 标题
 * @returns {Promise}
 */
export const createKnowledge = (fileId, title) => {
  return post(API_ENDPOINTS.KNOWLEDGE.CREATE, {
    file_id: fileId,
    title: title
  })
}

/**
 * 查询知识库列表
 * @param {number} page - 页码
 * @param {number} pageSize - 页容量
 * @param {string} title - 关键词（可选）
 * @returns {Promise}
 */
export const getKnowledgeList = (page = 1, pageSize = 10, title = '') => {
  const params = {
    page,
    page_size: pageSize
  }
  if (title && title.trim()) {
    params.title = title.trim()
  }
  return get(API_ENDPOINTS.KNOWLEDGE.LIST, params)
}

/**
 * 更新知识库
 * @param {number} knowledgeId - 知识库ID
 * @param {number} fileId - 文件ID
 * @param {string} title - 标题
 * @returns {Promise}
 */
export const updateKnowledge = (knowledgeId, fileId, title) => {
  return put(API_ENDPOINTS.KNOWLEDGE.UPDATE(knowledgeId), {
    file_id: fileId,
    title: title
  })
}

/**
 * 删除知识库
 * @param {number} knowledgeId - 知识库ID
 * @returns {Promise}
 */
export const deleteKnowledge = (knowledgeId) => {
  return del(API_ENDPOINTS.KNOWLEDGE.DELETE(knowledgeId))
}

/**
 * 下载知识库文件
 * @param {string} filepath - 文件路径
 * @param {string} filename - 文件名
 * @returns {Promise}
 */
export const downloadKnowledgeFile = async (filepath, filename) => {
  const { API_BASE_URL } = await import('@/config/api')
  
  // 构建完整的下载URL
  // 如果路径已经包含http://或https://，直接使用
  // 否则追加API_BASE_URL前缀
  let downloadUrl = filepath
  if (!filepath.startsWith('http://') && !filepath.startsWith('https://')) {
    // 确保路径正确拼接，避免重复斜杠
    const baseUrl = API_BASE_URL || ''
    const cleanPath = filepath.startsWith('/') ? filepath.substring(1) : filepath
    downloadUrl = baseUrl ? `${baseUrl}/${cleanPath}` : `/${cleanPath}`
  }
  
  // 使用axios直接请求，绕过response拦截器对blob的处理
  const axios = (await import('axios')).default
  
  // 从localStorage获取认证信息
  const authStore = localStorage.getItem('auth')
  let headers = {}
  if (authStore) {
    try {
      const auth = JSON.parse(authStore)
      if (auth.isAuthenticated && auth.user && auth.user.access_token) {
        const tokenType = auth.user.token_type || 'bearer'
        headers.Authorization = `${tokenType} ${auth.user.access_token}`
      }
    } catch (e) {
      console.error('解析认证信息失败', e)
    }
  }
  
  try {
    const response = await axios({
      method: 'get',
      url: downloadUrl,
      responseType: 'blob', // 重要：指定响应类型为blob
      headers
    })
    
    // 创建blob URL并触发下载
    const blob = new Blob([response.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = filename || 'download'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    return true
  } catch (error) {
    console.error('下载文件失败', error)
    throw error
  }
}


